//
//  PreferencesController.m
//  TwitterPlane
//
//  Created by kazuyuki takahashi on 10/02/15.
//  Copyright 2010 by invisibledesigner.com. All rights reserved.
//

#import "PreferencesController.h"
#import "TwitterEngineManager.h"
#import "OAConsumer+AppSpecific.h"
#import "OADataFetcher.h"
#import "OAToken_KeychainExtensions.h"


@implementation PreferencesController

+ (PreferencesController*)sharedController
{
    static dispatch_once_t pred = 0;
    static PreferencesController *controller = nil;
    
    dispatch_once(&pred, ^{
        controller = [[PreferencesController alloc] init];
    });
    return controller;
}

- (id)init
{
    self = [super initWithWindowNibName:@"Preferences"];
    return self;
}


- (void)showWindow:(id)sender
{
    [super showWindow:sender];
    
    OAToken *token = [[[OAToken alloc] initWithKeychainUsingAppName:@"twitplane"
                                                serviceProviderName:@"twitter"] autorelease];
    hasAccessToken_ = (token != nil);
}

- (void)windowWillClose:(NSNotification *)notification
{
    //PINCodeの再入力がされていたらaccesstokenを取得し直し
    if (!hasAccessToken_ && token_ && [[pinCodeField_ stringValue] length] > 0) {
        OAConsumer *consumer = [OAConsumer consumer];
        NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"];
        OAMutableURLRequest *req = [[[OAMutableURLRequest alloc] initWithURL:url
                                                                    consumer:consumer
                                                                       token:token_
                                                                       realm:nil
                                                           signatureProvider:nil] autorelease];
        [req setHTTPMethod:@"POST"];
        [req setOAuthParameterName:@"oauth_verifier"
                         withValue:[pinCodeField_ stringValue]];
        
        OADataFetcher *fetcher = [[[OADataFetcher alloc] init] autorelease];
        [fetcher fetchDataWithRequest:req
                             delegate:self
                    didFinishSelector:@selector(accessTokenTicket:didFinishWithData:)
                      didFailSelector:@selector(accessTokenTicket:failedWithError:)];
    }
    
    //clear
    [pinCodeField_ setStringValue:@""];
}

- (IBAction)authorize:(id)sender
{
    hasAccessToken_ = NO;
    
    OAConsumer *consumer = [OAConsumer consumer];
    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/oauth/request_token"];
    OAMutableURLRequest *req = [[[OAMutableURLRequest alloc] initWithURL:url
                                                                consumer:consumer
                                                                   token:nil
                                                                   realm:nil
                                                       signatureProvider:nil] autorelease];
    [req setHTTPMethod:@"POST"];
    
    OADataFetcher *fetcher = [[[OADataFetcher alloc] init] autorelease];
    [fetcher fetchDataWithRequest:req
                         delegate:self
                didFinishSelector:@selector(requestTokenTicket:didFinishWithData:)
                  didFailSelector:@selector(requestTokenTicket:failedWithError:)];
}

- (void)requestTokenTicket:(OAServiceTicket*)ticket didFinishWithData:(NSData*)data
{
    if ([ticket didSucceed]) {
        NSString *resbody = [[[NSString alloc] initWithData:data
                                                   encoding:NSUTF8StringEncoding] autorelease];
        [token_ release];
        token_ = [[OAToken alloc] initWithHTTPResponseBody:resbody];
        
        NSString *urlstr = [@"https://api.twitter.com/oauth/authorize?oauth_token=" 
                            stringByAppendingString:[token_ key]];
        NSURL *url = [NSURL URLWithString:urlstr];
        [[NSWorkspace sharedWorkspace] openURL:url];
    }
}

- (void)requestTokenTicket:(OAServiceTicket*)ticket failedWithError:(NSError*)error
{
    [[NSAlert alertWithError:error] runModal];
}

- (void)accessTokenTicket:(OAServiceTicket*)ticket didFinishWithData:(NSData*)data
{
    if ([ticket didSucceed]) {
        NSString *resbody = [[[NSString alloc] initWithData:data
                                                   encoding:NSUTF8StringEncoding] autorelease];
        //keychainに保存
        OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:resbody] autorelease];
        [token storeInDefaultKeychainWithAppName:@"twitplane" serviceProviderName:@"twitter"];
        
        //リロード
        [[TwitterEngineManager defaultManager] reloadAllFollowedTimeline];
        
        [[TwitterEngineManager defaultManager] checkUserCredentials];
    }
}

- (void)accessTokenTicket:(OAServiceTicket*)ticket failedWithError:(NSError*)error
{
    [[NSAlert alertWithMessageText:@"認証できませんでした。"
                     defaultButton:@"OK"
                   alternateButton:nil
                       otherButton:nil
         informativeTextWithFormat:@"", nil] runModal];
}


- (void)dealloc
{
    [token_ release];
    [super dealloc];
}


@end
